﻿using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;

namespace Domain_Home
{
	public abstract class Hosts
	{
		private static readonly string HostsFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), @"drivers\etc\hosts");

		public static void Add(string host, string destination)
		{
			var redundant = false;
			try
			{
				var reader = new StreamReader(File.Open(HostsFile, FileMode.Open, FileAccess.Read));
				while (!reader.EndOfStream && !redundant)
				{
					var line = new HostsLine(reader.ReadLine());
					redundant = !line.IsComment && line.Host.Equals(host) && line.Destination.Equals(destination);
				}
				reader.Close();
				if (!redundant)
				{
					var writer = new StreamWriter(File.Open(HostsFile, FileMode.Append, FileAccess.Write));
					writer.WriteLine(destination + " " + host);
					writer.Flush();
					writer.Close();
				}
			}
			catch (IOException)
			{
				Console.WriteLine("Access failed");
				Thread.Sleep(1000);
				Add(host, destination);
			}
		}

		public static void Remove(string host, string destination)
		{
			var temp = HostsFile + ".tmp";
			try
			{
				var reader = new StreamReader(File.Open(HostsFile, FileMode.Open, FileAccess.Read));
				var writer = new StreamWriter(File.Open(temp, FileMode.Create, FileAccess.Write));
				while (!reader.EndOfStream)
				{
					var line = new HostsLine(reader.ReadLine());
					if (line.IsComment || !line.IsComment && !(line.Host.Equals(host) && line.Destination.Equals(destination)))
					{
						writer.WriteLine(line.ToString());
					}
				}
				reader.Close();
				writer.Flush();
				writer.Close();
				File.Replace(temp, HostsFile, HostsFile + ".bak");
			}
			catch (IOException)
			{
				Console.WriteLine("Access failed");
				Thread.Sleep(1000);
				Remove(host, destination);
			}
		}
	}
}